<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>角色编辑框</title>
</head>
<body>
	<div>
		<fieldset class="layui-elem-field layui-field-title"
			style="margin-top: 10px;">
			<legend>基础信息</legend>
		</fieldset>
		<form class="layui-form" id="add-form">
			<div class="layui-form-item">
				<label class="layui-form-label">角色名</label>
				<div class="layui-input-block">
					<input type="text" name="rolename" lay-verify="rolename"
						autocomplete="off" placeholder="请输入 角色名" class="layui-input"
						id="rolename">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">权限</label>
				<div class="layui-input-block" id="permission"></div>
			</div>
			<div class="layui-form-item layui-form-text">
				<label class="layui-form-label">描述</label>
				<div class="layui-input-block">
					<textarea id="description" name="description"
						placeholder="请输入对该角色的描述" class="layui-textarea"></textarea>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn layui-btn-small" lay-submit=""
						lay-filter="demo3">确定</button>
					<button type="reset"
						class="layui-btn layui-btn-primary layui-btn-small">重置</button>
				</div>
			</div>
		</form>
	</div>
	<script>
		layui.config({
			base : 'plugins/layui/modules/'
		}).use([ 'form' ], function() {
			var form = layui.form(),
				$ = layui.jquery,
				layer = layui.layer;
	
			var cupermission = [],
				norepeat = {};
			//加载permission
			$.ajax({
				url : 'allPermissions',
				type : "GET",
				async : false,
				success : function(info) {
					$('#permission').html('');
					cupermission = info;
					for (var i in info) {
						name = info[i].name;
						$('#permission').append('<input type="checkbox" name=' + name + ' title=' + name + '>')
					}
				}
			});
			//保证重新加载后  样式也更新
			$('#add-form')[0].reset();
	
			//自定义验证规则
			form.verify({
				rolename : function(value) {
					if (value.length < 2) {
						return '角色名请大于两个字符';
					}
				},
				description : function(value) {
					if (value.length < 2) {
						return '描述请大于连个字符';
					}
				}
			});
	
			//监听提交
			form.on('submit(demo3)', function(data) {
				if (JSON.stringify(norepeat) != JSON.stringify(data.field)) {
					var json = {
						"name" : $('#rolename').val(),
						"description" : $('#description').val(),
						"permission" : []
					};
					for (var i in data.field) {
						for (var j in cupermission) {
							if (cupermission[j].name == i) {
								json.permission.push(cupermission[j]);
							}
						}
					}
					norepeat = data.field;
	
					$.ajax({
						url : 'addRole',
						type : "POST",
						data : JSON.stringify(json),
						async : false,
						dataType : 'json',
						contentType : 'application/json;charset=utf-8',
						success : function(info) {
							layer.msg('添加成功！');
							$('#add-form')[0].reset();
						}
					});
	
				}
				return false;
			});
		});
	</script>
</body>

</html>